<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :show-before="true">
        <span slot="before">共{{ total }}条记录</span>
        <template slot="after">
          <el-button size="small" type="warning" @click="$router.push('/import')">导入</el-button>
          <el-button size="small" type="danger" @click="exportExcel">导出</el-button>
          <el-button v-if="checkPerm('addEmployee')" size="small" type="primary" @click="isShowDialog= true">新增员工</el-button>
        </template>
      </page-tools>
      <!-- 放置表格和分页 -->
      <el-card>
        <el-table :data="employeeList" border>
          <el-table-column type="index" :index="customIndex" label="序号" sortable="" />
          <el-table-column label="头像" sortable="" width="200px">
            <template v-slot="{row}">
              <img v-fiximg="require('@/assets/common/head.jpg')" class="avatar" :src="row.staffPhoto" alt="">
            </template>
          </el-table-column>
          <el-table-column prop="username" label="姓名" sortable="" />
          <el-table-column prop="mobile" label="手机" sortable="" />
          <el-table-column prop="workNumber" label="工号" sortable="" />
          <el-table-column prop="formOfEmployment" label="聘用形式" sortable="" :formatter="formatEmployment" />
          <el-table-column prop="departmentName" label="部门" sortable="" />
          <el-table-column label="入职时间" sortable="">
            <template v-slot="{row}">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" sortable="">
            <template v-slot="{row}">
              <el-switch
                v-model="row.enableState"
                :active-value="1"
                :inactive-value="0"
                disabled
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template v-slot="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="assingRole(row.id)">角色</el-button>
              <el-button type="text" size="small" @click="delEmployeesFn(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination :total="total" :page-size="pageConfig.size" layout="prev, pager, next" @current-change="currentChange" />
        </el-row>
      </el-card>
      <addEmployees ref="refEmploye" :is-show-dialog="isShowDialog" @btnCancel="btnCancel" />
      <AssignRole ref="refAssingRole" :is-show-role.sync="isShowRole" />
    </div>
  </div>
</template>

<script>
import { export_json_to_excel } from '@/vendor/Export2Excel'
import addEmployees from './components/add-employees.vue'
import EmployeeEnum from '@/api/constant/employees'
import { getEmployeesList, delEmployee } from '@/api/employees'
import { formatDate } from '@/filters'
import AssignRole from './components/assign-role.vue'
export default {
  components: {
    addEmployees,
    AssignRole
  },
  data() {
    return {
      pageConfig: {
        page: 1,
        size: 5
      },
      employeeList: [],
      total: 0,
      isShowDialog: false,
      isShowRole: false
    }
  },
  created() {
    this.loadPage()
  },
  methods: {
    // 角色分配
    async assingRole(id) {
      await this.$refs.refAssingRole.assignRoleID(id)
      this.isShowRole = true
    },
    // 导出
    async exportExcel() {
      const { rows } = await getEmployeesList({ page: 1, size: this.total })
      // console.log(rows)

      // 3. 数据转换
      const dict = {
        '手机号': 'mobile',
        '姓名': 'username',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      // Object.keys  方法把传入的对象键名自动组成数组
      // header表头
      const header = Object.keys(dict)
      // console.log(header)
      // data 数据
      const data = rows.map(item => {
        const arr = []
        for (const key in dict) {
          if (dict[key] === 'formOfEmployment') {
            // 聘用形式处理
            const val = item[dict[key]]
            const red = EmployeeEnum.hireType.find(item => item.id === val)
            arr.push(red ? red.value : '未知')
          } else if (dict[key] === 'timeOfEntry' || dict[key] === 'correctionTime') {
            // 日期处理 使用过滤函数
            const val = item[dict[key]]
            arr.push(formatDate(val))
          } else {
            // 按照字典的顺序, 拿到每个属性, 推入数组中
            arr.push(item[dict[key]])
          }
        }
        return arr
      })
      // 调用生成工具下载 excel
      export_json_to_excel({ header, data })
    },
    // 取消弹窗
    async btnCancel() {
      await this.$refs.refEmploye.resetFields()
      this.$parent.isShowDialog = false
    },
    // 删除
    async  delEmployeesFn(id) {
      await this.$confirm('是否确定要删除?')
      await delEmployee(id)
      this.$message.success('操作成功')
      this.loadPage()
    },
    // 序号拼接
    customIndex(index) {
      return (this.pageConfig.page - 1) * this.pageConfig.size + index + 1
    },
    // 获取数据
    async loadPage() {
      const { rows, total } = await getEmployeesList(this.pageConfig)
      this.employeeList = rows
      this.total = total
    },
    // 切换页面
    currentChange(newpage) {
      this.pageConfig.page = newpage
      this.loadPage()
    },
    // 玫举数据
    formatEmployment(row, column, cellValue, index) {
      // row 行数据, column 列数据, cellValue 格子数据, index 索引
      // 格式化函数的特点是, 会议这个函数的返回值替换原来的数据
      // find 方法查找如果有则会返回玫举形式结果
      const res = EmployeeEnum.hireType.find(item => item.id === cellValue)
      // 如果没有就返回未知
      return res ? res.value : '未知形式'
    }
  }
}
</script>

<style lang="scss" scoped>
.avatar {
  width: 180px;
  height: 80px;
  // object-fit:cover contain;
  object-fit: contain;
}
</style>
